Homework · Runs in your browser
The training-at-scale calculator: memory by ZeRO stage, accumulation, loss scaling, all-reduce, pipeline bubble, checkpointing and cost
Build the calculators you would reach for when planning a large training run, with nothing but the standard library: bytes per parameter by ZeRO stage and a fit check, the linear-scaling learning rate with warmup, a gradient-accumulation routine that equals the full-batch gradient, the average micro-batch variance, half-precision rounding with loss-scaled gradients and a dynamic loss scale, ring and central all-reduce times, the pipeline bubble, activation-checkpointing units, data-loader step time, the best checkpoint interval, and the compute and days estimate. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest. Every function has its rules in the docstring.
Hints:
- Memory: stage 0 keeps weights, gradients and optimizer states on every device. Stage 1 divides the optimizer states by dp, stage 2 also the gradients, stage 3 everything. Check: 7.5 billion parameters on 64 devices give 120, 31.4, 16.6 and 1.9 GB for stages 0 to 3.
- Fit: add the model state, the activations and the overhead, and an exact match still fits.
- Learning rate: the target is base_lr x batch / base_batch. During warmup the rate climbs in a straight line from base_lr at step 0 to the target at step warmup_steps. Check: 0.1 at batch 256, batch 8192, 5000 warmup steps gives 0.72 at step 1000.
- Accumulation: add up per-sample gradients chunk by chunk and divide by the total number of samples once. A short last chunk then counts for its size. The answer must match mse_gradient for every micro_size.
- Variance: each chunk’s population variance counts once, whatever its length.
- Half precision: struct.pack(“<e”, x) rounds to half precision and raises OverflowError for values that are too large; return infinity with the right sign. fp16_gradient multiplies by the scale, rounds, and divides by the scale again, and reports an overflow as it is.
- Loss scale: an overflow multiplies the scale by the back-off factor and resets the good-step count. A clean step adds one, and reaching the growth interval multiplies by the growth factor and resets the count.
- All-reduce: ring is 2 (n - 1) / n x size / bandwidth plus 2 (n - 1) x latency, and one device takes 0 seconds. Central is 2 (n - 1) x size / bandwidth. Check: 14e9 bytes, 8 devices, 50e9 bytes per second gives 0.49 s for the ring.
- Bubble: (p - 1) / (m + p - 1). The smallest number of microbatches for a target counts an exact match as meeting it. Check: 8 stages and 10% need 63.
- Checkpointing: the peak is k + ceil(n / k) units. The best k is the smallest that gives the lowest peak. Check: 100 layers give k = 10 and 20 units.
- Loader: a step takes the larger of compute and load / workers. Check: compute 0.25 s, load 0.9 s needs 4 workers.
- Checkpoint interval: lost share = write / interval + interval / (2 x mtbf), best interval = sqrt(2 x write x mtbf).
- Compute: 6 x params x tokens. Compute-optimal with D = ratio x N gives N = sqrt(flops / (6 x ratio)). Check: 5.88e23 FLOPs at ratio 20 gives 7e10 parameters and 1.4e12 tokens.
- Try it: change the lesson script to a 13B model on 16 devices and predict which ZeRO stages fit an 80 GB device with 30 GB of activations before you run it.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
import math
import struct
def state_bytes_per_param(stage, dp, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
"""Bytes of model state held by ONE device, per parameter, under ZeRO-style sharding.
The defaults are mixed-precision Adam: 2 (fp16 weights) + 2 (fp16 gradients) + 12
(fp32 master weights, momentum and variance) = 16 bytes per parameter.
stage 0: nothing sharded (plain data parallel, every device holds everything).
stage 1: optimizer states divided by dp.
stage 2: gradients and optimizer states divided by dp.
stage 3: weights, gradients and optimizer states all divided by dp.
stage must be 0, 1, 2 or 3, dp a whole number >= 1, and no byte count negative,
otherwise ValueError.
"""
if stage not in (0, 1, 2, 3):
raise ValueError("stage must be 0, 1, 2 or 3")
if not isinstance(dp, int) or isinstance(dp, bool) or dp < 1:
raise ValueError("dp must be a whole number >= 1")
if weight_bytes < 0 or grad_bytes < 0 or optimizer_bytes < 0:
raise ValueError("byte counts must not be negative")
w, g, o = float(weight_bytes), float(grad_bytes), float(optimizer_bytes)
if stage == 0:
return w + g + o
if stage == 1:
return w + g + o / dp
if stage == 2:
return w + (g + o) / dp
return (w + g + o) / dp
def model_state_gb(params, dp, stage, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
"""Model-state memory per device in gigabytes (1 GB = 10**9 bytes).
params is the parameter count and must not be negative (ValueError otherwise).
"""
if params < 0:
raise ValueError("params must not be negative")
per = state_bytes_per_param(stage, dp, weight_bytes, grad_bytes, optimizer_bytes)
return params * per / 1e9
def fits_on_gpu(params, dp, stage, gpu_gb, activation_gb=0.0, overhead_gb=0.0, **bytes_kw):
"""True when model state + activations + overhead fit in gpu_gb (equal counts as fitting).
bytes_kw may carry weight_bytes, grad_bytes and optimizer_bytes. Negative gpu_gb,
activation_gb or overhead_gb raise ValueError.
"""
if gpu_gb < 0 or activation_gb < 0 or overhead_gb < 0:
raise ValueError("memory sizes must not be negative")
total = model_state_gb(params, dp, stage, **bytes_kw) + activation_gb + overhead_gb
return total <= gpu_gb
def scaled_lr(base_lr, base_batch, batch, step, warmup_steps):
"""Learning rate at `step` under the linear scaling rule with gradual warmup.
Target rate = base_lr x (batch / base_batch). During warmup (step < warmup_steps) the rate
rises in a straight line from base_lr at step 0 to the target at step warmup_steps.
From warmup_steps on (or when warmup_steps is 0) it is the target. base_lr, base_batch and
batch must be > 0, step >= 0 and warmup_steps >= 0, otherwise ValueError.
"""
if base_lr <= 0 or base_batch <= 0 or batch <= 0:
raise ValueError("base_lr, base_batch and batch must be positive")
if step < 0 or warmup_steps < 0:
raise ValueError("step and warmup_steps must not be negative")
target = base_lr * (batch / base_batch)
if warmup_steps == 0 or step >= warmup_steps:
return target
return base_lr + (target - base_lr) * (step / warmup_steps)
def mse_gradient(w, b, xs, ys):
"""Gradient (dw, db) of the MEAN squared error of the line y = w x + b over the samples.
loss = mean((w x + b - y)^2). xs and ys must have the same non-zero length, else ValueError.
"""
if len(xs) != len(ys) or len(xs) == 0:
raise ValueError("xs and ys must have the same non-zero length")
n = len(xs)
dw = db = 0.0
for x, y in zip(xs, ys):
err = w * x + b - y
dw += 2.0 * err * x
db += 2.0 * err
return dw / n, db / n
def accumulated_gradient(w, b, xs, ys, micro_size):
"""The same gradient as mse_gradient, built from micro-batches of at most micro_size samples.
Walk the samples in order in chunks of micro_size (the last chunk may be smaller), add up
every chunk's per-sample gradients, and divide by the TOTAL number of samples once at the
end, so a short last chunk is weighted by its size. micro_size must be a whole number >= 1
and the inputs as in mse_gradient, otherwise ValueError.
"""
if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
raise ValueError("micro_size must be a whole number >= 1")
if len(xs) != len(ys) or len(xs) == 0:
raise ValueError("xs and ys must have the same non-zero length")
total_w = total_b = 0.0
for start in range(0, len(xs), micro_size):
cx = xs[start:start + micro_size]
cy = ys[start:start + micro_size]
gw, gb = mse_gradient(w, b, cx, cy)
total_w += gw * len(cx)
total_b += gb * len(cx)
n = len(xs)
return total_w / n, total_b / n
def micro_batch_variance_mean(values, micro_size):
"""Average of the per-micro-batch population variances (each chunk counts once).
This is what a batch-norm layer would see if it computed statistics on each micro-batch
separately. Chunks of micro_size in order, last chunk may be smaller. Empty values or
micro_size < 1 raise ValueError.
"""
if len(values) == 0:
raise ValueError("values must not be empty")
if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
raise ValueError("micro_size must be a whole number >= 1")
variances = []
for start in range(0, len(values), micro_size):
chunk = values[start:start + micro_size]
m = sum(chunk) / len(chunk)
variances.append(sum((v - m) ** 2 for v in chunk) / len(chunk))
return sum(variances) / len(variances)
def to_fp16(x):
"""Round a Python float to the nearest IEEE half-precision value and return it as a float.
Values too large for half precision (beyond what rounds to 65504) become +inf or -inf.
Tiny values round to a subnormal or to 0.0. nan and inf pass through.
"""
try:
return struct.unpack("<e", struct.pack("<e", x))[0]
except OverflowError:
return math.inf if x > 0 else -math.inf
def fp16_gradient(grad, scale):
"""The gradient a half-precision backward pass would hand to the optimizer.
The loss is multiplied by `scale`, so the gradient arrives as grad x scale rounded to half
precision; it is then divided by `scale` again in higher precision. Return that recovered
value. If the scaled gradient overflowed half precision (inf or nan), return it as is, so
the caller can see the overflow. scale must be > 0, otherwise ValueError.
"""
if scale <= 0:
raise ValueError("scale must be positive")
scaled = to_fp16(grad * scale)
if math.isinf(scaled) or math.isnan(scaled):
return scaled
return scaled / scale
def next_loss_scale(scale, found_inf, good_steps, growth_factor=2.0, backoff_factor=0.5,
growth_interval=2000):
"""One update of a dynamic loss scale. Returns (new_scale, new_good_steps).
If found_inf: multiply the scale by backoff_factor and reset good_steps to 0 (the step is
skipped by the caller). Otherwise count one more good step; when the count reaches
growth_interval, multiply the scale by growth_factor and reset the count to 0.
"""
if found_inf:
return scale * backoff_factor, 0
good_steps += 1
if good_steps >= growth_interval:
return scale * growth_factor, 0
return scale, good_steps
def ring_allreduce_seconds(size_bytes, n, bandwidth, latency=0.0):
"""Time for a ring all-reduce of size_bytes over n devices.
Each device sends and receives 2 (n - 1) / n x size_bytes in total, in 2 (n - 1) steps:
time = 2 (n - 1) / n x size_bytes / bandwidth + 2 (n - 1) x latency.
bandwidth is bytes per second per link, latency seconds per step. One device (n == 1) takes
0.0 seconds. n < 1, bandwidth <= 0, or negative size or latency raise ValueError.
"""
if not isinstance(n, int) or isinstance(n, bool) or n < 1:
raise ValueError("n must be a whole number >= 1")
if bandwidth <= 0 or size_bytes < 0 or latency < 0:
raise ValueError("bandwidth must be positive, size and latency not negative")
if n == 1:
return 0.0
return 2.0 * (n - 1) / n * size_bytes / bandwidth + 2.0 * (n - 1) * latency
def central_allreduce_seconds(size_bytes, n, bandwidth):
"""Time when one device collects every other device's data and sends the sum back.
The central device's link carries (n - 1) x size_bytes in and (n - 1) x size_bytes out, one
after the other: time = 2 (n - 1) x size_bytes / bandwidth. One device takes 0.0 seconds.
Same input checks as ring_allreduce_seconds (without latency).
"""
if not isinstance(n, int) or isinstance(n, bool) or n < 1:
raise ValueError("n must be a whole number >= 1")
if bandwidth <= 0 or size_bytes < 0:
raise ValueError("bandwidth must be positive, size not negative")
return 2.0 * (n - 1) * size_bytes / bandwidth
def bubble_fraction(stages, microbatches):
"""Share of the whole pipelined step that a stage sits idle: (p - 1) / (m + p - 1).
p = stages, m = microbatches, both whole numbers >= 1, otherwise ValueError.
"""
for v in (stages, microbatches):
if not isinstance(v, int) or isinstance(v, bool) or v < 1:
raise ValueError("stages and microbatches must be whole numbers >= 1")
return (stages - 1) / (microbatches + stages - 1)
def microbatches_for_bubble(stages, target):
"""Smallest number of microbatches whose bubble_fraction is at most target.
target must satisfy 0 < target < 1 (ValueError otherwise). For stages == 1 the answer is 1.
A bubble exactly equal to target counts as meeting it.
"""
if not 0 < target < 1:
raise ValueError("target must be between 0 and 1")
if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
raise ValueError("stages must be a whole number >= 1")
m = 1
while (stages - 1) > target * (m + stages - 1) + 1e-12:
m += 1
return m
def activation_units(n_layers, k):
"""Peak stored activations, in units of one layer's activations, with k checkpoints.
The network is cut into k segments. The k segment boundaries stay in memory, and while one
segment is recomputed in the backward pass its own layers are held too, so the peak is
k + ceil(n_layers / k). n_layers >= 1 and 1 <= k <= n_layers, otherwise ValueError.
"""
if not isinstance(n_layers, int) or isinstance(n_layers, bool) or n_layers < 1:
raise ValueError("n_layers must be a whole number >= 1")
if not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= n_layers:
raise ValueError("k must be a whole number between 1 and n_layers")
return k + -(-n_layers // k)
def best_checkpoint_count(n_layers):
"""The k that minimises activation_units(n_layers, k); the smallest k on a tie."""
best_k = 1
best = activation_units(n_layers, 1)
for k in range(2, n_layers + 1):
u = activation_units(n_layers, k)
if u < best:
best, best_k = u, k
return best_k
def recompute_overhead(forward=1.0, backward=2.0):
"""Extra compute from re-running one forward pass: forward / (forward + backward).
Costs must be >= 0 with forward + backward > 0, otherwise ValueError.
"""
if forward < 0 or backward < 0 or forward + backward <= 0:
raise ValueError("costs must not be negative and must not both be zero")
return forward / (forward + backward)
def loader_step_time(compute_s, load_s, workers):
"""Seconds per training step when loading overlaps compute.
One batch takes load_s seconds for one worker, and `workers` workers load in parallel, so
a batch is ready every load_s / workers seconds. A step takes the slower of that and
compute_s. workers must be a whole number >= 1 and times >= 0, otherwise ValueError.
"""
if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1:
raise ValueError("workers must be a whole number >= 1")
if compute_s < 0 or load_s < 0:
raise ValueError("times must not be negative")
return max(compute_s, load_s / workers)
def min_workers(compute_s, load_s):
"""Fewest loader workers (at least 1) for which loading is not slower than compute.
compute_s must be > 0 and load_s >= 0, otherwise ValueError. Exactly equal counts as enough.
"""
if compute_s <= 0 or load_s < 0:
raise ValueError("compute_s must be positive and load_s not negative")
w = 1
while load_s / w > compute_s + 1e-12:
w += 1
return w
def wasted_fraction(interval, write, mtbf):
"""First-order share of time lost to checkpointing and failures.
write / interval (time spent writing checkpoints) + interval / (2 x mtbf) (on average half
an interval of work is redone per failure). interval, write and mtbf share one unit and
must be > 0 (ValueError otherwise).
"""
if interval <= 0 or write <= 0 or mtbf <= 0:
raise ValueError("interval, write and mtbf must be positive")
return write / interval + interval / (2.0 * mtbf)
def best_interval(write, mtbf):
"""The interval minimising wasted_fraction: sqrt(2 x write x mtbf)."""
if write <= 0 or mtbf <= 0:
raise ValueError("write and mtbf must be positive")
return math.sqrt(2.0 * write * mtbf)
def training_flops(params, tokens):
"""Rule-of-thumb training compute: 6 x params x tokens floating-point operations."""
if params < 0 or tokens < 0:
raise ValueError("params and tokens must not be negative")
return 6.0 * params * tokens
def training_days(flops, gpus, peak_flops_per_gpu, utilisation):
"""Days to run `flops` on `gpus` devices at utilisation x peak_flops_per_gpu each.
gpus must be a whole number >= 1, peak_flops_per_gpu > 0, 0 < utilisation <= 1, and flops
>= 0, otherwise ValueError.
"""
if not isinstance(gpus, int) or isinstance(gpus, bool) or gpus < 1:
raise ValueError("gpus must be a whole number >= 1")
if peak_flops_per_gpu <= 0 or not 0 < utilisation <= 1 or flops < 0:
raise ValueError("bad peak, utilisation or flops")
return flops / (gpus * peak_flops_per_gpu * utilisation) / 86400.0
def compute_optimal(flops, tokens_per_param=20.0):
"""Model size N and token count D that spend `flops` with D = tokens_per_param x N.
Using flops = 6 N D, so N = sqrt(flops / (6 x tokens_per_param)) and D = tokens_per_param x N.
Return (N, D). flops >= 0 and tokens_per_param > 0, otherwise ValueError.
"""
if flops < 0 or tokens_per_param <= 0:
raise ValueError("flops must not be negative and tokens_per_param must be positive")
n = math.sqrt(flops / (6.0 * tokens_per_param))
return n, tokens_per_param * n
Show the tests (test_starter.py)
import math
import pytest
from starter import (
accumulated_gradient,
activation_units,
best_checkpoint_count,
best_interval,
bubble_fraction,
central_allreduce_seconds,
compute_optimal,
fits_on_gpu,
fp16_gradient,
loader_step_time,
micro_batch_variance_mean,
microbatches_for_bubble,
min_workers,
model_state_gb,
mse_gradient,
next_loss_scale,
recompute_overhead,
ring_allreduce_seconds,
scaled_lr,
state_bytes_per_param,
to_fp16,
training_days,
training_flops,
wasted_fraction,
)
def close(a, b, tol=1e-9):
return abs(a - b) <= tol * max(1.0, abs(a), abs(b))
# ---- memory budget -----------------------------------------------------------
def test_state_bytes_default_is_sixteen_without_sharding():
assert state_bytes_per_param(0, 1) == 16.0
assert state_bytes_per_param(0, 64) == 16.0
for stage in (1, 2, 3):
assert state_bytes_per_param(stage, 1) == 16.0
def test_state_bytes_by_stage():
assert close(state_bytes_per_param(1, 8), 2 + 2 + 12 / 8)
assert close(state_bytes_per_param(2, 8), 2 + 14 / 8)
assert close(state_bytes_per_param(3, 8), 16 / 8)
assert close(state_bytes_per_param(1, 64), 4 + 12 / 64)
assert close(state_bytes_per_param(2, 64), 2 + 14 / 64)
assert close(state_bytes_per_param(3, 64), 0.25)
def test_state_bytes_stages_only_ever_shrink_memory():
for dp in (2, 4, 16, 128):
values = [state_bytes_per_param(s, dp) for s in (0, 1, 2, 3)]
for a, b in zip(values, values[1:]):
assert b < a
def test_state_bytes_custom_byte_counts():
assert state_bytes_per_param(0, 1, 4, 4, 8) == 16.0
assert state_bytes_per_param(0, 1, 2, 2, 0) == 4.0
assert close(state_bytes_per_param(1, 4, 4, 4, 8), 4 + 4 + 2)
assert close(state_bytes_per_param(2, 4, 4, 4, 8), 4 + 12 / 4)
assert close(state_bytes_per_param(3, 4, 4, 4, 8), 4)
assert close(state_bytes_per_param(3, 2, 1, 3, 5), 4.5)
assert close(state_bytes_per_param(2, 2, 1, 3, 5), 1 + 8 / 2)
def test_state_bytes_returns_a_float_not_an_integer_division():
assert state_bytes_per_param(1, 3) == pytest.approx(4 + 4.0)
assert state_bytes_per_param(3, 3) == pytest.approx(16 / 3)
assert isinstance(state_bytes_per_param(0, 1), float)
def test_state_bytes_validation():
for stage in (-1, 4, 1.5):
with pytest.raises(ValueError):
state_bytes_per_param(stage, 4)
for dp in (0, -2, 2.0):
with pytest.raises(ValueError):
state_bytes_per_param(1, dp)
with pytest.raises(ValueError):
state_bytes_per_param(0, 1, -1, 2, 12)
with pytest.raises(ValueError):
state_bytes_per_param(0, 1, 2, -1, 12)
with pytest.raises(ValueError):
state_bytes_per_param(0, 1, 2, 2, -12)
def test_model_state_gb_matches_the_worked_examples():
assert close(model_state_gb(1.5e9, 1, 0), 24.0)
assert close(model_state_gb(7e9, 1, 0), 112.0)
assert close(model_state_gb(70e9, 1, 0), 1120.0)
assert close(model_state_gb(7.5e9, 64, 0), 120.0)
assert close(model_state_gb(7.5e9, 64, 1), 31.40625)
assert close(model_state_gb(7.5e9, 64, 2), 16.640625)
assert close(model_state_gb(7.5e9, 64, 3), 1.875)
assert model_state_gb(0, 8, 2) == 0.0
def test_model_state_gb_passes_byte_counts_through():
assert close(model_state_gb(1e9, 1, 0, 4, 4, 8), 16.0)
assert close(model_state_gb(1e9, 2, 3, 4, 4, 8), 8.0)
assert close(model_state_gb(2e9, 1, 0, weight_bytes=1, grad_bytes=1, optimizer_bytes=0), 4.0)
def test_model_state_gb_validation():
with pytest.raises(ValueError):
model_state_gb(-1, 1, 0)
with pytest.raises(ValueError):
model_state_gb(1e9, 0, 0)
with pytest.raises(ValueError):
model_state_gb(1e9, 1, 5)
def test_fits_on_gpu_is_inclusive_and_adds_all_three_parts():
assert fits_on_gpu(1e9, 1, 0, 16.0) is True
assert fits_on_gpu(1e9, 1, 0, 15.9) is False
assert fits_on_gpu(1e9, 1, 0, 20.0, 4.0) is True
assert fits_on_gpu(1e9, 1, 0, 19.9, 4.0) is False
assert fits_on_gpu(1e9, 1, 0, 20.0, 2.0, 2.0) is True
assert fits_on_gpu(1e9, 1, 0, 19.9, 2.0, 2.0) is False
assert fits_on_gpu(1e9, 1, 0, 20.0, 0.0, 4.0) is True
assert fits_on_gpu(1e9, 1, 0, 19.0, 0.0, 4.0) is False
def test_fits_on_gpu_uses_sharding_and_byte_options():
assert fits_on_gpu(7e9, 8, 0, 80, 20, 4) is False
assert fits_on_gpu(7e9, 8, 1, 80, 20, 4) is True
assert fits_on_gpu(7e9, 8, 3, 15.0) is True
assert fits_on_gpu(7e9, 8, 3, 13.9) is False
assert fits_on_gpu(1e9, 1, 0, 8.0, weight_bytes=4, grad_bytes=4, optimizer_bytes=0) is True
assert fits_on_gpu(1e9, 1, 0, 7.9, weight_bytes=4, grad_bytes=4, optimizer_bytes=0) is False
def test_fits_on_gpu_validation():
with pytest.raises(ValueError):
fits_on_gpu(1e9, 1, 0, -1.0)
with pytest.raises(ValueError):
fits_on_gpu(1e9, 1, 0, 80.0, -1.0)
with pytest.raises(ValueError):
fits_on_gpu(1e9, 1, 0, 80.0, 1.0, -1.0)
# ---- batch size and learning rate --------------------------------------------
def test_scaled_lr_linear_scaling_after_warmup():
assert close(scaled_lr(0.1, 256, 8192, 5000, 5000), 3.2)
assert close(scaled_lr(0.1, 256, 8192, 9000, 5000), 3.2)
assert close(scaled_lr(0.1, 256, 512, 100, 10), 0.2)
assert close(scaled_lr(0.1, 256, 256, 100, 10), 0.1)
assert close(scaled_lr(0.1, 256, 128, 100, 10), 0.05)
assert close(scaled_lr(0.3, 100, 400, 0, 0), 1.2)
def test_scaled_lr_ramps_in_a_straight_line_during_warmup():
assert close(scaled_lr(0.1, 256, 8192, 0, 5000), 0.1)
assert close(scaled_lr(0.1, 256, 8192, 1000, 5000), 0.72)
assert close(scaled_lr(0.1, 256, 8192, 2500, 5000), 1.65)
assert close(scaled_lr(0.1, 256, 8192, 4999, 5000), 0.1 + 3.1 * 4999 / 5000)
assert close(scaled_lr(1.0, 10, 20, 5, 10), 1.5)
def test_scaled_lr_warmup_never_decreases_and_starts_at_base():
prev = 0.0
for step in range(0, 21):
v = scaled_lr(0.05, 64, 640, step, 20)
assert v >= prev
prev = v
assert close(scaled_lr(0.05, 64, 640, 0, 20), 0.05)
assert close(scaled_lr(0.05, 64, 640, 20, 20), 0.5)
def test_scaled_lr_with_a_smaller_batch_ramps_down_toward_the_target():
assert close(scaled_lr(0.2, 100, 50, 0, 10), 0.2)
assert close(scaled_lr(0.2, 100, 50, 5, 10), 0.15)
assert close(scaled_lr(0.2, 100, 50, 10, 10), 0.1)
def test_scaled_lr_no_warmup_jumps_straight_to_the_target():
assert close(scaled_lr(0.1, 256, 8192, 0, 0), 3.2)
assert close(scaled_lr(0.1, 256, 8192, 7, 0), 3.2)
def test_scaled_lr_validation():
for args in ((0, 256, 512, 0, 0), (0.1, 0, 512, 0, 0), (0.1, 256, 0, 0, 0),
(-0.1, 256, 512, 0, 0), (0.1, 256, 512, -1, 0), (0.1, 256, 512, 0, -1)):
with pytest.raises(ValueError):
scaled_lr(*args)
# ---- gradient accumulation ---------------------------------------------------
XS = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
YS = [1.2, 1.9, 3.1, 3.8, 5.3, 5.9, 7.2, 7.8, 9.1, 9.9]
def test_mse_gradient_hand_computed():
gw, gb = mse_gradient(1.0, 0.0, [1.0, 2.0], [0.0, 0.0])
assert close(gw, 5.0)
assert close(gb, 3.0)
gw, gb = mse_gradient(2.0, 1.0, [1.0], [3.0])
assert close(gw, 0.0) and close(gb, 0.0)
gw, gb = mse_gradient(0.0, 0.0, [3.0], [2.0])
assert close(gw, -12.0) and close(gb, -4.0)
def test_mse_gradient_matches_the_lesson_numbers():
gw, gb = mse_gradient(0.5, 0.0, XS, YS)
assert close(gw, -28.885, 1e-9)
assert close(gb, -8.29, 1e-9)
def test_mse_gradient_is_a_mean_not_a_sum():
one = mse_gradient(0.5, 0.0, [1.0], [2.0])
many = mse_gradient(0.5, 0.0, [1.0] * 7, [2.0] * 7)
assert close(one[0], many[0]) and close(one[1], many[1])
def test_mse_gradient_validation():
with pytest.raises(ValueError):
mse_gradient(0, 0, [], [])
with pytest.raises(ValueError):
mse_gradient(0, 0, [1.0], [1.0, 2.0])
def test_accumulated_gradient_equals_the_full_batch_for_every_micro_size():
full = mse_gradient(0.5, 0.0, XS, YS)
for micro in (1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 100):
got = accumulated_gradient(0.5, 0.0, XS, YS, micro)
assert close(got[0], full[0], 1e-9), micro
assert close(got[1], full[1], 1e-9), micro
def test_accumulated_gradient_weights_a_short_last_chunk_by_its_size():
xs = [1.0, 1.0, 1.0, 1.0, 1.0, 9.0]
ys = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
full = mse_gradient(1.0, 0.5, xs, ys)
got = accumulated_gradient(1.0, 0.5, xs, ys, 5)
assert close(got[0], full[0]) and close(got[1], full[1])
unweighted_w = (mse_gradient(1.0, 0.5, xs[:5], ys[:5])[0] + mse_gradient(1.0, 0.5, xs[5:], ys[5:])[0]) / 2
assert abs(got[0] - unweighted_w) > 1.0
def test_accumulated_gradient_other_models_and_orderings():
xs = [3.0, -1.0, 2.0, 0.0, 5.0]
ys = [1.0, 4.0, -2.0, 0.5, 2.0]
for w, b in ((0.0, 0.0), (-2.0, 3.0), (1.5, -0.5)):
full = mse_gradient(w, b, xs, ys)
for micro in (1, 2, 3, 5):
got = accumulated_gradient(w, b, xs, ys, micro)
assert close(got[0], full[0]) and close(got[1], full[1])
def test_accumulated_gradient_does_not_change_its_inputs():
xs = list(XS)
ys = list(YS)
accumulated_gradient(0.5, 0.0, xs, ys, 3)
assert xs == XS and ys == YS
def test_accumulated_gradient_validation():
for micro in (0, -1, 2.0):
with pytest.raises(ValueError):
accumulated_gradient(0, 0, XS, YS, micro)
with pytest.raises(ValueError):
accumulated_gradient(0, 0, [], [], 1)
with pytest.raises(ValueError):
accumulated_gradient(0, 0, [1.0, 2.0], [1.0], 1)
def test_micro_batch_variance_mean_values():
vals = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
assert close(micro_batch_variance_mean(vals, 8), 5.25)
assert close(micro_batch_variance_mean(vals, 4), 1.25)
assert close(micro_batch_variance_mean(vals, 2), 0.25)
assert close(micro_batch_variance_mean(vals, 1), 0.0)
assert close(micro_batch_variance_mean(vals, 100), 5.25)
def test_micro_batch_variance_mean_short_last_chunk_counts_once():
assert close(micro_batch_variance_mean([0.0, 2.0, 5.0], 2), (1.0 + 0.0) / 2)
assert close(micro_batch_variance_mean([0.0, 2.0, 4.0, 10.0, 12.0], 3), ((8 / 3) + 1.0) / 2)
def test_micro_batch_variance_mean_is_population_variance():
assert close(micro_batch_variance_mean([1.0, 3.0], 2), 1.0)
def test_micro_batch_variance_mean_validation():
with pytest.raises(ValueError):
micro_batch_variance_mean([], 2)
for micro in (0, -3, 1.5):
with pytest.raises(ValueError):
micro_batch_variance_mean([1.0, 2.0], micro)
# ---- mixed precision ---------------------------------------------------------
def test_to_fp16_limits():
assert to_fp16(65504.0) == 65504.0
assert to_fp16(65519.0) == 65504.0
assert to_fp16(65520.0) == math.inf
assert to_fp16(70000.0) == math.inf
assert to_fp16(-70000.0) == -math.inf
assert to_fp16(-1e30) == -math.inf
assert to_fp16(1e-9) == 0.0
assert to_fp16(0.0) == 0.0
assert to_fp16(-1e-9) == 0.0 and math.copysign(1.0, to_fp16(-1e-9)) == -1.0
def test_to_fp16_rounding_and_subnormals():
assert to_fp16(1.0) == 1.0
assert to_fp16(1.0 + 0.0001) == 1.0
assert to_fp16(1.0 + 0.001) == 1.0009765625
assert to_fp16(2 ** -24) == 2 ** -24
assert to_fp16(3e-8) == 2 ** -24
assert to_fp16(2 ** -25 * 0.99) == 0.0
assert to_fp16(0.1) == 0.0999755859375
assert to_fp16(2049.0) == 2048.0
assert to_fp16(2051.0) == 2052.0
def test_to_fp16_passes_special_values():
assert to_fp16(math.inf) == math.inf
assert to_fp16(-math.inf) == -math.inf
assert math.isnan(to_fp16(math.nan))
def test_fp16_gradient_underflow_and_rescue():
assert fp16_gradient(1e-8, 1) == 0.0
assert close(fp16_gradient(1e-8, 1024), 1.0013580322265625e-05 / 1024)
assert close(fp16_gradient(1e-8, 65536), 9.997e-09, 1e-3)
assert close(fp16_gradient(3e-8, 1), 2 ** -24)
assert close(fp16_gradient(3e-8, 1024), 3e-8, 1e-2)
assert close(fp16_gradient(1e-5, 1), 1.0013580322265625e-05)
def test_fp16_gradient_divides_by_the_scale_exactly_once():
assert fp16_gradient(1.0, 8) == 1.0
assert fp16_gradient(0.5, 4) == 0.5
assert fp16_gradient(-2.0, 1024) == -2.0
assert fp16_gradient(0.25, 65536.0 / 16) == 0.25
def test_fp16_gradient_reports_overflow():
assert fp16_gradient(2.0, 65536) == math.inf
assert fp16_gradient(-2.0, 65536) == -math.inf
assert fp16_gradient(2.0, 8192) == 2.0
assert fp16_gradient(1.0, 65504.0) == 1.0
assert fp16_gradient(1.0, 70000.0) == math.inf
assert math.isnan(fp16_gradient(math.nan, 4))
assert fp16_gradient(math.inf, 4) == math.inf
def test_fp16_gradient_validation():
for scale in (0, -1.0):
with pytest.raises(ValueError):
fp16_gradient(1.0, scale)
def test_next_loss_scale_backs_off_on_overflow():
assert next_loss_scale(65536.0, True, 7) == (32768.0, 0)
assert next_loss_scale(8.0, True, 0, backoff_factor=0.25) == (2.0, 0)
assert next_loss_scale(1.0, True, 1999) == (0.5, 0)
def test_next_loss_scale_counts_good_steps_and_grows():
assert next_loss_scale(1024.0, False, 0) == (1024.0, 1)
assert next_loss_scale(1024.0, False, 1997) == (1024.0, 1998)
assert next_loss_scale(1024.0, False, 1998) == (1024.0, 1999)
assert next_loss_scale(1024.0, False, 1999) == (2048.0, 0)
assert next_loss_scale(1024.0, False, 2, growth_interval=3) == (2048.0, 0)
assert next_loss_scale(1024.0, False, 1, growth_interval=3) == (1024.0, 2)
assert next_loss_scale(10.0, False, 4, growth_factor=3.0, growth_interval=5) == (30.0, 0)
assert next_loss_scale(10.0, False, 5, growth_interval=5) == (20.0, 0)
def test_next_loss_scale_trace_matches_the_lesson():
scale, good = 65536.0, 0
seen = []
for found in (False, True, False, False, False, False, False, True, False):
scale, good = next_loss_scale(scale, found, good, growth_interval=3)
seen.append(scale)
assert seen == [65536.0, 32768.0, 32768.0, 32768.0, 65536.0, 65536.0, 65536.0, 32768.0, 32768.0]
def test_next_loss_scale_overflow_resets_progress_toward_growth():
scale, good = 100.0, 0
for _ in range(2):
scale, good = next_loss_scale(scale, False, good, growth_interval=3)
scale, good = next_loss_scale(scale, True, good, growth_interval=3)
assert (scale, good) == (50.0, 0)
for _ in range(2):
scale, good = next_loss_scale(scale, False, good, growth_interval=3)
assert (scale, good) == (50.0, 2)
# ---- communication -----------------------------------------------------------
def test_ring_allreduce_bandwidth_term():
assert close(ring_allreduce_seconds(14e9, 8, 50e9), 0.49)
assert close(ring_allreduce_seconds(14e9, 2, 50e9), 0.28)
assert close(ring_allreduce_seconds(14e9, 64, 50e9), 2 * 63 / 64 * 0.28)
assert close(ring_allreduce_seconds(100.0, 4, 10.0), 15.0)
assert close(ring_allreduce_seconds(0.0, 4, 10.0), 0.0)
def test_ring_allreduce_latency_term_counts_two_steps_per_hop():
assert close(ring_allreduce_seconds(0.0, 4, 10.0, 0.5), 3.0)
assert close(ring_allreduce_seconds(100.0, 4, 10.0, 0.5), 18.0)
assert close(ring_allreduce_seconds(14e9, 1024, 50e9, 5e-6), 0.5697, 1e-3)
def test_ring_allreduce_is_nearly_flat_in_the_device_count():
t8 = ring_allreduce_seconds(1e9, 8, 1e10)
t1024 = ring_allreduce_seconds(1e9, 1024, 1e10)
assert t1024 > t8
assert t1024 < 2 * 1e9 / 1e10 + 1e-12
def test_ring_allreduce_single_device_costs_nothing():
assert ring_allreduce_seconds(1e9, 1, 1e9) == 0.0
assert ring_allreduce_seconds(1e9, 1, 1e9, 1.0) == 0.0
def test_ring_allreduce_validation():
for n in (0, -2, 2.0):
with pytest.raises(ValueError):
ring_allreduce_seconds(1.0, n, 1.0)
for bw in (0, -1.0):
with pytest.raises(ValueError):
ring_allreduce_seconds(1.0, 4, bw)
with pytest.raises(ValueError):
ring_allreduce_seconds(-1.0, 4, 1.0)
with pytest.raises(ValueError):
ring_allreduce_seconds(1.0, 4, 1.0, -1.0)
def test_central_allreduce_grows_with_the_device_count():
assert close(central_allreduce_seconds(14e9, 2, 50e9), 0.56)
assert close(central_allreduce_seconds(14e9, 8, 50e9), 3.92)
assert close(central_allreduce_seconds(14e9, 64, 50e9), 35.28)
assert central_allreduce_seconds(1e9, 1, 1e9) == 0.0
assert close(central_allreduce_seconds(100.0, 3, 10.0), 40.0)
def test_central_is_never_faster_than_ring_for_more_than_two_devices():
for n in (3, 4, 16, 256):
assert central_allreduce_seconds(1e9, n, 1e9) > ring_allreduce_seconds(1e9, n, 1e9)
assert close(central_allreduce_seconds(1e9, 2, 1e9), 2 * ring_allreduce_seconds(1e9, 2, 1e9))
def test_central_allreduce_validation():
with pytest.raises(ValueError):
central_allreduce_seconds(1.0, 0, 1.0)
with pytest.raises(ValueError):
central_allreduce_seconds(1.0, 2, 0.0)
with pytest.raises(ValueError):
central_allreduce_seconds(-1.0, 2, 1.0)
# ---- pipeline bubble ---------------------------------------------------------
def test_bubble_fraction_values():
assert bubble_fraction(1, 1) == 0.0
assert bubble_fraction(1, 10) == 0.0
assert close(bubble_fraction(4, 1), 0.75)
assert close(bubble_fraction(4, 4), 3 / 7)
assert close(bubble_fraction(4, 16), 3 / 19)
assert close(bubble_fraction(8, 32), 7 / 39)
assert close(bubble_fraction(8, 64), 7 / 71)
assert close(bubble_fraction(2, 1), 0.5)
def test_bubble_fraction_shrinks_with_microbatches_and_grows_with_stages():
prev = 1.0
for m in range(1, 40):
v = bubble_fraction(6, m)
assert v < prev
prev = v
prev = -1.0
for p in range(1, 40):
v = bubble_fraction(p, 8)
assert v > prev
prev = v
def test_bubble_fraction_validation():
for bad in ((0, 4), (4, 0), (-1, 4), (4, 2.0), (2.0, 4)):
with pytest.raises(ValueError):
bubble_fraction(*bad)
def test_microbatches_for_bubble_values():
assert microbatches_for_bubble(2, 0.10) == 9
assert microbatches_for_bubble(4, 0.10) == 27
assert microbatches_for_bubble(8, 0.10) == 63
assert microbatches_for_bubble(16, 0.10) == 135
assert microbatches_for_bubble(4, 0.5) == 3
assert microbatches_for_bubble(1, 0.1) == 1
assert microbatches_for_bubble(2, 0.5) == 1
def test_microbatches_for_bubble_is_the_smallest_that_works():
for p in (2, 3, 5, 8):
for target in (0.05, 0.2, 0.3333, 0.6):
m = microbatches_for_bubble(p, target)
assert bubble_fraction(p, m) <= target + 1e-12
if m > 1:
assert bubble_fraction(p, m - 1) > target
def test_microbatches_for_bubble_validation():
for target in (0, 1, -0.1, 1.5):
with pytest.raises(ValueError):
microbatches_for_bubble(4, target)
with pytest.raises(ValueError):
microbatches_for_bubble(0, 0.1)
# ---- activation checkpointing ------------------------------------------------
def test_activation_units_values():
assert activation_units(100, 1) == 101
assert activation_units(100, 10) == 20
assert activation_units(100, 100) == 101
assert activation_units(10, 3) == 3 + 4
assert activation_units(10, 4) == 4 + 3
assert activation_units(7, 7) == 8
assert activation_units(1, 1) == 2
assert activation_units(16, 4) == 8
def test_activation_units_rounds_the_segment_up():
assert activation_units(11, 5) == 5 + 3
assert activation_units(9, 4) == 4 + 3
assert activation_units(1000, 28) == 28 + 36
def test_activation_units_validation():
for bad in ((0, 1), (10, 0), (10, 11), (-5, 1), (10.0, 2), (10, 2.0)):
with pytest.raises(ValueError):
activation_units(*bad)
def test_best_checkpoint_count_values():
assert best_checkpoint_count(16) == 4
assert best_checkpoint_count(100) == 10
assert best_checkpoint_count(1000) == 28
assert best_checkpoint_count(1) == 1
assert best_checkpoint_count(2) == 1
assert best_checkpoint_count(3) == 1
def test_best_checkpoint_count_is_a_true_minimum_and_the_smallest_on_ties():
for n in (5, 12, 30, 50, 99, 257):
k = best_checkpoint_count(n)
best = activation_units(n, k)
for other in range(1, n + 1):
assert activation_units(n, other) >= best
for smaller in range(1, k):
assert activation_units(n, smaller) > best
def test_best_checkpoint_count_is_close_to_the_square_root():
for n in (49, 400, 900):
assert abs(best_checkpoint_count(n) - math.sqrt(n)) <= 1
def test_recompute_overhead_values():
assert close(recompute_overhead(), 1 / 3)
assert close(recompute_overhead(1, 1), 0.5)
assert close(recompute_overhead(1.0, 3.0), 0.25)
assert recompute_overhead(0.0, 2.0) == 0.0
assert recompute_overhead(2.0, 0.0) == 1.0
assert close(recompute_overhead(3.0, 6.0), 1 / 3)
def test_recompute_overhead_validation():
with pytest.raises(ValueError):
recompute_overhead(-1.0, 2.0)
with pytest.raises(ValueError):
recompute_overhead(1.0, -2.0)
with pytest.raises(ValueError):
recompute_overhead(0.0, 0.0)
# ---- data loading ------------------------------------------------------------
def test_loader_step_time_takes_the_slower_side():
assert close(loader_step_time(0.25, 0.9, 1), 0.9)
assert close(loader_step_time(0.25, 0.9, 2), 0.45)
assert close(loader_step_time(0.25, 0.9, 3), 0.3)
assert close(loader_step_time(0.25, 0.9, 4), 0.25)
assert close(loader_step_time(0.25, 0.9, 8), 0.25)
assert close(loader_step_time(1.0, 0.0, 1), 1.0)
assert close(loader_step_time(0.0, 2.0, 4), 0.5)
def test_loader_step_time_never_drops_below_compute_and_never_rises_with_workers():
prev = float("inf")
for w in range(1, 20):
v = loader_step_time(0.4, 2.0, w)
assert v >= 0.4
assert v <= prev
prev = v
def test_loader_step_time_validation():
for w in (0, -1, 2.0):
with pytest.raises(ValueError):
loader_step_time(0.2, 0.5, w)
with pytest.raises(ValueError):
loader_step_time(-0.2, 0.5, 1)
with pytest.raises(ValueError):
loader_step_time(0.2, -0.5, 1)
def test_min_workers_values():
assert min_workers(0.25, 0.9) == 4
assert min_workers(0.25, 1.0) == 4
assert min_workers(0.25, 1.01) == 5
assert min_workers(1.0, 0.5) == 1
assert min_workers(1.0, 1.0) == 1
assert min_workers(0.1, 0.0) == 1
assert min_workers(0.3, 0.9) == 3
assert min_workers(0.1, 0.7) == 7
def test_min_workers_is_the_smallest_that_keeps_up():
for compute, load in ((0.2, 0.7), (0.5, 1.6), (0.07, 0.5), (1.0, 5.0)):
w = min_workers(compute, load)
assert loader_step_time(compute, load, w) == pytest.approx(compute)
if w > 1:
assert loader_step_time(compute, load, w - 1) > compute
def test_min_workers_validation():
with pytest.raises(ValueError):
min_workers(0.0, 1.0)
with pytest.raises(ValueError):
min_workers(-1.0, 1.0)
with pytest.raises(ValueError):
min_workers(1.0, -1.0)
# ---- checkpoints and failures ------------------------------------------------
def test_wasted_fraction_values():
assert close(wasted_fraction(60.0, 3.0, 360.0), 3 / 60 + 60 / 720)
assert close(wasted_fraction(5.0, 3.0, 360.0), 0.6 + 5 / 720)
assert close(wasted_fraction(240.0, 3.0, 360.0), 3 / 240 + 240 / 720)
assert close(wasted_fraction(10.0, 1.0, 100.0), 0.1 + 0.05)
assert close(wasted_fraction(20.0, 2.0, 50.0), 0.1 + 0.2)
def test_wasted_fraction_has_a_minimum_at_the_best_interval():
write, mtbf = 3.0, 360.0
b = best_interval(write, mtbf)
at_best = wasted_fraction(b, write, mtbf)
assert wasted_fraction(b * 0.5, write, mtbf) > at_best
assert wasted_fraction(b * 2.0, write, mtbf) > at_best
assert wasted_fraction(b * 0.9, write, mtbf) > at_best
assert wasted_fraction(b * 1.1, write, mtbf) > at_best
def test_wasted_fraction_validation():
for args in ((0, 1, 1), (1, 0, 1), (1, 1, 0), (-1, 1, 1)):
with pytest.raises(ValueError):
wasted_fraction(*args)
def test_best_interval_values():
assert close(best_interval(3.0, 360.0), math.sqrt(2160.0))
assert close(best_interval(1.0, 50.0), 10.0)
assert close(best_interval(2.0, 4.0), 4.0)
assert close(best_interval(8.0, 1.0), 4.0)
def test_best_interval_validation():
with pytest.raises(ValueError):
best_interval(0.0, 10.0)
with pytest.raises(ValueError):
best_interval(1.0, 0.0)
# ---- compute and scaling -----------------------------------------------------
def test_training_flops_is_six_n_d():
assert training_flops(7e9, 1e12) == pytest.approx(4.2e22)
assert training_flops(70e9, 1.4e12) == pytest.approx(5.88e23)
assert training_flops(280e9, 300e9) == pytest.approx(5.04e23)
assert training_flops(1, 1) == 6.0
assert training_flops(0, 1e12) == 0.0
assert training_flops(10, 0) == 0.0
def test_training_flops_validation():
with pytest.raises(ValueError):
training_flops(-1, 5)
with pytest.raises(ValueError):
training_flops(5, -1)
def test_training_days_values():
f = training_flops(7e9, 1e12)
assert close(training_days(f, 1024, 3e14, 0.4), 3.95598235, 1e-6)
assert close(training_days(f, 256, 3e14, 0.4), 15.82392940, 1e-6)
assert close(training_days(86400.0, 1, 1.0, 1.0), 1.0)
assert close(training_days(86400.0, 2, 1.0, 1.0), 0.5)
assert close(training_days(86400.0, 1, 2.0, 1.0), 0.5)
assert close(training_days(86400.0, 1, 1.0, 0.5), 2.0)
assert training_days(0.0, 4, 1.0, 1.0) == 0.0
def test_training_days_validation():
for args in ((1.0, 0, 1.0, 0.5), (1.0, 2.0, 1.0, 0.5), (1.0, 2, 0.0, 0.5), (1.0, 2, 1.0, 0.0),
(1.0, 2, 1.0, 1.5), (-1.0, 2, 1.0, 0.5)):
with pytest.raises(ValueError):
training_days(*args)
def test_compute_optimal_recovers_the_chinchilla_point():
n, d = compute_optimal(5.88e23)
assert close(n, 7e10, 1e-9)
assert close(d, 1.4e12, 1e-9)
assert close(d / n, 20.0)
def test_compute_optimal_other_ratios_and_consistency():
n, d = compute_optimal(6.0 * 100.0 * 10.0, 10.0)
assert close(n, 10.0) and close(d, 100.0)
for c in (1e18, 3.3e21, 8e24):
n, d = compute_optimal(c)
assert close(6.0 * n * d, c)
assert close(d, 20.0 * n)
n, d = compute_optimal(5.04e23)
assert close(n, 6.481e10, 1e-3)
assert close(d, 1.296e12, 1e-3)
n1, d1 = compute_optimal(1e22, 10.0)
n2, d2 = compute_optimal(1e22, 40.0)
assert n1 > n2 and d1 < d2
assert compute_optimal(0.0) == (0.0, 0.0)
def test_compute_optimal_validation():
with pytest.raises(ValueError):
compute_optimal(-1.0)
with pytest.raises(ValueError):
compute_optimal(1e20, 0.0)