Systems Specialization · CPU ReferenceCPU reference; target qualification separateLesson 5 of 8 in Phase 16

Phase 16 / Workload operations

Capacity, utilization, and operating cost

Revision v0.18.1 ·

Lesson · about 90 minutes · CPU practice

Measure end-to-end local service time at more than one workload length. Compute offered load, worker reserve and illustrative cost with consistent units.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Changes, rollback, and artifact provenance
Hardware: CPU

Setup help: Python, notebook, or Cloud TPU VM

Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.

Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.

macOS / Linux terminal · repository folder
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txt

PowerShell · repository folder
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txt

After activation, run the complete worked example from that same folder:

macOS / Linux terminal · activated environment
python phases/16-operations/05-capacity-utilization-and-operating-cost/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/16-operations/05-capacity-utilization-and-operating-cost/code/main.py

For an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.

Check: Three actual local durations feed a first-order plan whose arrival rate, worker count, reserve and price are explicitly hypothetical. No hardware utilization or cloud-cost claim is inferred from CPU timings.

Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.

Stage 1 of 5 · Understand the MechanismCore mental model, equations & visual walkthrough

What you will be able to do

  • Measure end-to-end local service time at more than one workload length.
  • Compute offered load, worker reserve and illustrative cost with consistent units.
  • Identify assumptions that prevent a CPU fixture from establishing accelerator fleet capacity.

The problem

A short local training job finishes quickly. How many workers would a stream of jobs require, and what can this measurement actually tell us about cost? We will measure complete CPU jobs of several lengths, separate update work from startup overhead and apply transparent capacity arithmetic to explicitly hypothetical arrival rates and prices.

The idea

Operating cost depends on resource allocation, runtime and the billing model. A workload's fraction of time in useful updates is not the same as device utilization. Keep cost accounting and performance measurements explicit.

Account for billed time as well as useful work

A fresh job pays for imports, initialization, compilation, updates, logging and checkpoint writes. The update timer covers only one part of that lifecycle. If you size workers from the inner update time alone, you omit work the process still has to finish.

The two panels compare fresh jobs with 88, 3232 and 6464 updates. Their separate vertical scales reveal that synchronized updates occupy a small fraction of the complete local job. Small differences among the wall-time bars can change across captures; this is not a scaling benchmark. First decide whether your planned service launches a new process for each job or reuses a warm worker.

Measure the service boundary you intend to provision

The supervisor starts its clock before child launch and stops after exit. That interval includes Python/JAX startup, compilation warmup, updates, logging and checkpoints. The inner timer begins after ready and waits for each update to complete, so those two durations have deliberately different boundaries.

Follow the 88-update category across the two panels. Both bars summarize the same job, but the lower one accounts for only its synchronized update intervals. The remainder is time outside that timer, not a measurement of idle hardware. A persistent warm worker removes or amortizes some fixed costs and therefore needs a separately measured service-time distribution.

Convert seconds into worker demand

For arrival rate λ\lambda per hour and tt seconds of service per job, offered demand is λt/3600\lambda t/3600 worker-hours per hour. With 1,200 arrivals and 6 seconds each, demand is 2 worker-hours each hour. At a 40% reserve, usable capacity is 0.6 per worker, so ⌈2/0.6⌉=4\lceil2/0.6\rceil=4 workers in this simplified model. The arithmetic describes average demand; it does not predict burst queues or latency tails.

ρ=λt3600m\rho=\frac{\lambda t}{3600m}

State the reserve rather than hiding it

Reserve reduces the capacity you plan to use. A 40%40\% reserve leaves a usable fraction of 1−0.4=0.61-0.4=0.6 per worker. For the preceding demand of 22 worker-hours per hour, three workers provide 1.81.8 usable worker-hours, which is insufficient; four provide 2.42.4. Rounding the worker count up is part of the decision, not a display preference.

State what the reserve is intended to cover, such as maintenance or variation in offered work. It does not automatically protect a latency target during bursts. Retain the arrival and service-time assumptions so a later measurement can challenge this average-demand plan.

mmin=⌈λt3600(1−r)⌉m_{\min}=\left\lceil\frac{\lambda t}{3600(1-r)}\right\rceil

A cost number needs a declared price model

Suppose a worker costs a hypothetical 1.501.50 currency units per reserved hour. Holding the four workers from the worked plan for one hour costs 4×1.50=64\times1.50=6, whether they are busy for the entire hour or not. Charging only the six seconds spent on an individual job answers an active-time allocation question; it does not account for reserved idle capacity.

Keep the rate, billing interval and provisioned duration explicit. Real estimates also need failed attempts, storage, transfer and the provider's current billing rules. The rate here is an arithmetic assumption, not a quoted cloud price.

Do not confuse duty fraction with hardware utilization

Define application duty fraction for this measurement as synchronized update time divided by complete job time. For an illustrative job taking 22 seconds end to end with 0.020.02 seconds in that update interval, the fraction is 0.02/2=0.010.02/2=0.01, or 1%1\%. These example values explain the ratio; read the plotted capture for its actual durations.

The remaining time can include imports, compilation, logging and checkpoint work. The ratio does not reveal CPU-core occupancy, accelerator utilization, bandwidth or allocated-but-idle device time. Use it to choose which stage to inspect next, and use device-specific evidence for hardware utilization.

Capacity is a distribution, not just a mean

An average can conceal very different queue behavior. Consider a changed, hypothetical workload where 80%80\% of jobs take 11 second and 20%20\% take 1010. The mean is 0.8×1+0.2×10=2.80.8\times1+0.2\times10=2.8 seconds, while most jobs finish quickly and the slow group can hold a worker much longer. A plan based only on the mean misses which users wait behind that group.

Retain individual service times and replay representative arrivals with the routing and retry policy you intend to use. Include unavailable workers and burst periods before judging a latency objective. The three local measurements demonstrate complete-process accounting; they are too few to estimate a production high percentile.

Read the figure

Both panels use the categories 88, 3232 and 6464 updates in fresh child processes. The upper axis is complete job seconds. The lower axis is summed synchronized update seconds. They have separate linear scales, so equal-looking bar heights across panels do not mean equal durations.

Choose one category and compare its two numerical axis readings. The update interval is only a small part of its complete lifecycle. Then compare categories within a panel. Since each job starts a new process and the sample is tiny, a non-monotone wall-time ordering can reflect fixed costs and host variation rather than the cost of an extra update.

Connect it to the computation

The upper clock includes startup, initialization, warmup, updates, logging and checkpoints; the lower clock counts only synchronized updates. Their ratio is an application duty fraction under those boundaries. It is not hardware utilization.

Predict how the picture would change for a worker that stays warm for many jobs: some startup and compilation costs could be shared instead of repaid for each category. Measure that actual lifecycle before replacing the current service-time assumption in the capacity calculation. Keep the workload's arrival rate, reserve and hypothetical price separate from the measured local durations.

Figure data and execution details

Recorded environment: JAX 0.9.2 · 1 CPU device

The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.

Stage 2 of 5 · Build & Run the ReferenceStep-by-step code construction & verified execution output

Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.

1 Keep job duty tied to matching intervals

Read the timing numerator and denominator from the same run.

main.py · append build step 1
def update_duty(update_seconds, wall_seconds):
    return update_seconds / wall_seconds if wall_seconds else 0.

This fraction does not measure device occupancy.

2 Convert one job into modeled cost

Keep seconds, hourly rate and worker allocation explicit.

main.py · append build step 2
def cost_per_job(service_seconds, hourly_rate):
    return service_seconds / 3600 * hourly_rate

The rate is an assumption in this CPU fixture, not an invoice.

3 Apply reserve to offered worker-hours

Change arrivals while holding the local timing observations fixed.

main.py · append build step 3
def capacity(measured_job_s, arrivals_per_hour, workers, hourly_rate, reserve_fraction=.25):
    """Illustrative one-job-per-worker plan; inputs are not cloud price discovery."""
    values=[measured_job_s,arrivals_per_hour,hourly_rate,reserve_fraction]
    if any(not math.isfinite(x) for x in values) or measured_job_s <= 0 or arrivals_per_hour < 0 or hourly_rate < 0:
        raise ValueError('invalid finite capacity inputs')
    if not isinstance(workers,int) or isinstance(workers,bool) or workers < 1 or not 0 <= reserve_fraction < 1:
        raise ValueError('invalid workers or reserve')
    offered=arrivals_per_hour*measured_job_s/3600
    load=offered/workers
    required=max(1,math.ceil(offered/(1-reserve_fraction)))
    return dict(offered_worker_hours_per_hour=offered,load_fraction=load,
                minimum_workers_with_reserve=required,hourly_budget=workers*hourly_rate,
                hypothetical_cost_per_job=cost_per_job(measured_job_s,hourly_rate),
                within_reserve=load <= 1-reserve_fraction)

This estimate exposes the assumed reserve, arrival rate and price for review.

View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
def update_duty(update_seconds, wall_seconds):
    return update_seconds / wall_seconds if wall_seconds else 0.

def cost_per_job(service_seconds, hourly_rate):
    return service_seconds / 3600 * hourly_rate

def capacity(measured_job_s, arrivals_per_hour, workers, hourly_rate, reserve_fraction=.25):
    """Illustrative one-job-per-worker plan; inputs are not cloud price discovery."""
    values=[measured_job_s,arrivals_per_hour,hourly_rate,reserve_fraction]
    if any(not math.isfinite(x) for x in values) or measured_job_s <= 0 or arrivals_per_hour < 0 or hourly_rate < 0:
        raise ValueError('invalid finite capacity inputs')
    if not isinstance(workers,int) or isinstance(workers,bool) or workers < 1 or not 0 <= reserve_fraction < 1:
        raise ValueError('invalid workers or reserve')
    offered=arrivals_per_hour*measured_job_s/3600
    load=offered/workers
    required=max(1,math.ceil(offered/(1-reserve_fraction)))
    return dict(offered_worker_hours_per_hour=offered,load_fraction=load,
                minimum_workers_with_reserve=required,hourly_budget=workers*hourly_rate,
                hypothetical_cost_per_job=cost_per_job(measured_job_s,hourly_rate),
                within_reserve=load <= 1-reserve_fraction)

Run the example

python3 phases/16-operations/05-capacity-utilization-and-operating-cost/code/main.py
About this command

This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.

Inspect the complete assembled example
main.py · complete Python example
# Complete runnable example (operations-05)
"""Bounded local JAX subprocess supervisor and lifecycle verifier."""
from pathlib import Path
import hashlib
import json
import math
import os
import subprocess
import sys
import tempfile
import time


def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()


def atomic_json(path, value):
    """Replace one local JSON file only after its bytes have been flushed."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix=path.name+'.', suffix='.tmp', dir=path.parent)
    try:
        with os.fdopen(fd, 'w') as stream:
            json.dump(value, stream, sort_keys=True, allow_nan=False)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)

def update_duty(update_seconds, wall_seconds):
    return update_seconds / wall_seconds if wall_seconds else 0.

def cost_per_job(service_seconds, hourly_rate):
    return service_seconds / 3600 * hourly_rate

# This file is materialized only inside the caller-owned temporary run folder.
WORKER = r'''
import hashlib, json, os, sys, time
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
root = Path(sys.argv[1])
cfg = json.loads((root/'config.json').read_text())
worker_hash = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
def emit(event, **fields):
    print(json.dumps(dict(event=event, monotonic_s=time.monotonic(), **fields)), flush=True)
def digest(value):
    return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',', ':'),allow_nan=False).encode()).hexdigest()
def write_checkpoint(state):
    target = root/'checkpoint.json'
    temporary = root/'checkpoint.pending'
    with temporary.open('w') as stream:
        json.dump(dict(state,checksum=digest(state)),stream,sort_keys=True,allow_nan=False)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary,target)
    emit('checkpoint',step=state['step'],state_hash=digest(state))
try:
    emit('started',pid=os.getpid(),backend=jax.default_backend(),device_count=jax.device_count())
    if jax.default_backend() != cfg['backend'] or jax.device_count() < cfg['min_devices']:
        raise ValueError('runtime backend/device contract failed')
    x = jnp.linspace(-1.,1.,64)
    y = 2*x+1
    data_hash = digest(dict(x=np.asarray(x).tolist(),y=np.asarray(y).tolist()))
    training = {name:cfg[name] for name in ('seed','learning_rate','momentum','batch_size')}
    config_hash = digest(training)
    if cfg['resume']:
        saved = json.loads((root/'checkpoint.json').read_text())
        checksum = saved.pop('checksum',None)
        if checksum != digest(saved) or saved.get('worker_hash') != worker_hash:
            raise ValueError('checkpoint checksum/source mismatch')
        if saved['schema_version'] != 1 or saved['config_hash'] != config_hash or saved['data_hash'] != data_hash:
            raise ValueError('checkpoint provenance mismatch')
        state = saved
        step = saved['step']
        params=jnp.array(saved['params'])
        velocity=jnp.array(saved['velocity'])
        key=jnp.array(saved['key'],dtype=jnp.uint32)
        if not isinstance(step,int) or isinstance(step,bool) or step < 0 or step > cfg['steps'] or params.shape != (2,) or velocity.shape != (2,) or key.shape != (2,):
            raise ValueError('invalid checkpoint state shape or step')
        if not bool(jnp.all(jnp.isfinite(params))) or not bool(jnp.all(jnp.isfinite(velocity))):
            raise ValueError('nonfinite checkpoint state')
        emit('restored',step=step,state_hash=digest(saved))
    else:
        step=0
        params=jnp.zeros(2)
        velocity=jnp.zeros(2)
        key=jax.random.PRNGKey(cfg['seed'])
    def update(params,velocity,key):
        key, sample = jax.random.split(key)
        indices=jax.random.choice(sample,64,(cfg['batch_size'],),replace=False)
        objective=lambda p:jnp.mean((p[0]*x[indices]+p[1]-y[indices])**2)
        loss, grad=jax.value_and_grad(objective)(params)
        velocity=cfg['momentum']*velocity+grad
        params=params-cfg['learning_rate']*velocity
        return params,velocity,key,loss
    compiled=jax.jit(update)
    # Compile and synchronize once without consuming actual training state.
    begin=time.perf_counter()
    warm=compiled(params,velocity,key)
    jax.block_until_ready(warm)
    emit('ready',compile_warmup_s=time.perf_counter()-begin,step=step)
    while step < cfg['steps']:
        if cfg.get('stall_at') == step:
            emit('stall_injected',step=step)
            time.sleep(cfg.get('stall_seconds',10.))
        begin=time.perf_counter()
        params,velocity,key,loss=compiled(params,velocity,key)
        jax.block_until_ready((params,velocity,key,loss))
        elapsed=time.perf_counter()-begin
        step+=1
        state=dict(schema_version=1,worker_hash=worker_hash,step=step,params=np.asarray(params).tolist(),velocity=np.asarray(velocity).tolist(),key=np.asarray(key).tolist(),config_hash=config_hash,data_hash=data_hash)
        emit('progress',step=step,loss=float(loss),examples=cfg['batch_size'],update_s=elapsed,state_hash=digest(state))
        if step % cfg['checkpoint_every'] == 0 or step == cfg['steps']:
            write_checkpoint(state)
        if cfg.get('fail_after') == step:
            raise RuntimeError('controlled failure after update')
    write_checkpoint(state)
    emit('completed',step=step,state_hash=digest(state))
except Exception as error:
    emit('failed',kind=type(error).__name__,message=str(error))
    raise SystemExit(23)
'''

# Step 3 — Add bounded launch and result collection
def default_config(**changes):
    cfg=dict(seed=3,learning_rate=.04,momentum=.8,batch_size=8,steps=8,
             checkpoint_every=2,backend='cpu',min_devices=1,resume=False,
             fail_after=None,stall_at=None,stall_seconds=10.)
    # Apply configuration overrides before validating the resulting fields.
    cfg.update(changes)
    for name in ('steps','checkpoint_every','batch_size','min_devices'):
        if not isinstance(cfg[name],int) or isinstance(cfg[name],bool) or cfg[name] < 1:
            raise ValueError(name+' must be a positive integer')
    if cfg['batch_size'] > 64 or not 0 <= cfg['momentum'] < 1 or not 0 < cfg['learning_rate'] < 1:
        raise ValueError('invalid training configuration')
    return cfg


def launch(root, config=None, timeout=10.):
    root=Path(root)
    root.mkdir(parents=True,exist_ok=True)
    cfg=default_config(**(config or {}))
    if timeout <= 0:
        raise ValueError('timeout must be positive')
    atomic_json(root/'config.json',cfg)
    worker=root/'worker.py'
    worker.write_text(WORKER)
    env=dict(os.environ,JAX_PLATFORMS=cfg['backend'],PYTHONUNBUFFERED='1')
    started=time.perf_counter()
    process=subprocess.Popen([sys.executable,str(worker),str(root)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,env=env)
    timed_out=False
    try:
        stdout,stderr=process.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        timed_out=True
        process.terminate()
        try:
            stdout,stderr=process.communicate(timeout=1.)
        except subprocess.TimeoutExpired:
            process.kill()
            stdout,stderr=process.communicate(timeout=1.)
    wall=time.perf_counter()-started
    events=[]
    malformed=[]
    for line in stdout.splitlines():
        if not line.strip():
            continue
        try:
            event=json.loads(line)
            if not isinstance(event,dict) or 'event' not in event:
                raise ValueError('not an event')
            events.append(event)
        except (ValueError,TypeError):
            malformed.append(line)
    status='timed_out' if timed_out else 'completed' if process.returncode == 0 and not malformed and events and events[-1]['event']=='completed' else 'failed'
    result=dict(status=status,returncode=process.returncode,wall_s=wall,events=events,stderr=stderr,
                worker_hash=hashlib.sha256(WORKER.encode()).hexdigest(),config=cfg,malformed_stdout=malformed)
    atomic_json(root/'run.json',result)
    return result

# Step 4 — Add metric summaries and capacity arithmetic
def summarize(result):
    updates=[e for e in result['events'] if e['event']=='progress']
    checkpoints=[e['step'] for e in result['events'] if e['event']=='checkpoint']
    count=sum(e['examples'] for e in updates)
    update_s=sum(e['update_s'] for e in updates)
    latest=max((e['step'] for e in updates),default=0)
    checkpoint=max(checkpoints,default=0)
    return dict(status=result['status'],updates=len(updates),examples=count,last_step=latest,checkpoint_step=checkpoint,
                uncheckpointed_updates=max(0,latest-checkpoint),update_s=update_s,
                update_examples_per_s=count/update_s if update_s else 0.,
                job_examples_per_s=count/result['wall_s'] if result['wall_s'] else 0.,
                update_duty_fraction=update_duty(update_s,result['wall_s']))

def capacity(measured_job_s, arrivals_per_hour, workers, hourly_rate, reserve_fraction=.25):
    """Illustrative one-job-per-worker plan; inputs are not cloud price discovery."""
    values=[measured_job_s,arrivals_per_hour,hourly_rate,reserve_fraction]
    if any(not math.isfinite(x) for x in values) or measured_job_s <= 0 or arrivals_per_hour < 0 or hourly_rate < 0:
        raise ValueError('invalid finite capacity inputs')
    if not isinstance(workers,int) or isinstance(workers,bool) or workers < 1 or not 0 <= reserve_fraction < 1:
        raise ValueError('invalid workers or reserve')
    offered=arrivals_per_hour*measured_job_s/3600
    load=offered/workers
    required=max(1,math.ceil(offered/(1-reserve_fraction)))
    return dict(offered_worker_hours_per_hour=offered,load_fraction=load,
                minimum_workers_with_reserve=required,hourly_budget=workers*hourly_rate,
                hypothetical_cost_per_job=cost_per_job(measured_job_s,hourly_rate),
                within_reserve=load <= 1-reserve_fraction)

# Step 5 — Measure jobs before evaluating assumptions
samples=[]
# Keep this run’s database and artifacts in a scratch directory removed on exit.
with tempfile.TemporaryDirectory(prefix='ops-capacity-') as folder:
    for steps in [8,32,64]:
        run=launch(Path(folder)/str(steps),dict(steps=steps))
        assert run['status']=='completed'
        samples.append((steps,run,summarize(run)))
measured=max(run['wall_s'] for _,run,_ in samples)
plan=capacity(measured_job_s=measured,arrivals_per_hour=600,workers=2,hourly_rate=1.5,reserve_fraction=.25)
assert plan['hourly_budget']==3.
print('measured local job seconds:',[r['wall_s'] for _,r,_ in samples])
print('illustrative capacity plan:',plan)
print('assumptions: 600 arrivals/hour, 2 workers, hypothetical 1.50 per worker-hour, 25% reserve')

Expected result: Three actual local durations feed a first-order plan whose arrival rate, worker count, reserve and price are explicitly hypothetical. No hardware utilization or cloud-cost claim is inferred from CPU timings.

Recorded output and runtime details

Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.

2026-10-27T17:15:40.807623+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

measured local job seconds: [0.8413121248595417, 0.8365796250291169, 0.9017954594455659]
illustrative capacity plan: {'offered_worker_hours_per_hour': 0.15029924324092767, 'load_fraction': 0.07514962162046383, 'minimum_workers_with_reserve': 1, 'hourly_budget': 3.0, 'hypothetical_cost_per_job': 0.0003757481081023191, 'within_reserve': True}
assumptions: 600 arrivals/hour, 2 workers, hypothetical 1.50 per worker-hour, 25% reserve
nominal load at two demand scenarios: 0.07514962162046383 0.15029924324092767
required workers under changed hypothetical reserve: 1
PASS: operations-05

Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.

Stage 3 of 5 · Controlled ExperimentsPredict before running & test boundary conditions

Check units with known arithmetic

Check units with known arithmetic · Python experiment
# Experiment — Check units with known arithmetic
known=capacity(90.,80.,4,2.,.25)
assert known['offered_worker_hours_per_hour']==2.
assert known['load_fraction']==.5
assert known['minimum_workers_with_reserve']==3
assert known['hypothetical_cost_per_job']==.05
assert known['hourly_budget']==8.

Expected: Demand, load, reserve and cost match a hand calculation.

This independent arithmetic checks the calculator without treating invented inputs as measured infrastructure.

Double the arrivals without changing the job

Double the arrivals without changing the job · Python experiment
# Experiment — Double the arrivals without changing the job
one=capacity(measured,600,2,1.5,.25)
two=capacity(measured,1200,2,1.5,.25)
assert abs(two['load_fraction']-2*one['load_fraction'])<1e-12
assert two['hypothetical_cost_per_job']==one['hypothetical_cost_per_job']
print('nominal load at two demand scenarios:',one['load_fraction'],two['load_fraction'])

Expected: Nominal load doubles while per-job active-time cost stays fixed under the same simple model.

Demand changes the required capacity; it does not automatically make each job faster or slower in a model without contention.

Stage 4 of 5 · Hands-On Exercise & CheckpointModify the code yourself, solve transfer tasks & test your understanding
Hands-On Exercise · Modify & Verify Run in the declared lesson environment

Make it yours

Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.

Using the measured duration input, compute workers for 1,200 arrivals/hour, 40% reserve and a 1.5×1.5\times planning factor. Change arrivals to 2,400 while holding measured service time fixed. Interpret the resulting load and cost assumptions from the actual report.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • Arrival demand, measured service duration, reserve fraction, and proposed worker count.

Outputs

  • A minimum worker estimate and an independent utilization/load-bound check.

Invariants to check

  • Units are consistent; full reserve, nonpositive workers, and nonfinite service measurements are rejected.

Hints

  • Convert hourly arrivals to per-second demand before multiplying by service time.
  • Label price and demand as assumptions unless directly measured.
Your attempt · complete the TODOs
import math
import numpy as np

def required_worker_count(arrivals_per_hour, service_seconds, reserve_fraction, workers):
    """A minimum worker estimate and an independent utilization/load-bound check."""
    # TODO: Convert demand, service time, reserve, and worker count to consistent units before checking feasibility.
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution
changed=capacity(measured,1200,2,1.5,.4)
required=changed['minimum_workers_with_reserve']
demand=1200*measured/3600
assert demand/required <= .6 + 1e-12
if required>1: assert demand/(required-1) > .6
print('required workers under changed hypothetical reserve:',required)

Account for failed attempts

Transfer / diagnosis

Assume 100100 completed jobs require 125125 equal-duration attempts. Compare active-time cost per attempt with active-time cost per completion.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Assume 100100 completed jobs require 125125 equal-duration attempts. Compare active-time cost per attempt with active-time cost per completion.

Outputs

  • Cost per attempt and per successful completion.

Invariants to check

  • The two calculations differ only by their declared denominator.

Hints

  • Every attempt consumes resources under this hypothetical model.
  • Count all 125 attempts for attempt cost and 100 completions for completion cost.
Your attempt · complete the TODOs
import math

def practice_account_for_failed_attempts(completed_jobs, total_attempts, attempt_seconds):
    """Complete the account for failed attempts check."""
    # TODO: ('Compute active-time cost per attempt and per completion from 125 equal-duration attempts for 100 completed jobs.', 'Both cost denominators and their distinct totals.', 'Attempt cost uses all attempts; completion cost uses only successful completions.')
    raise NotImplementedError
Show a hint

Every attempt consumes resources under this hypothetical model.

Reveal reference solution and reasoning
Account for failed attempts · Python solution
# Account for failed attempts (Transfer / diagnosis)
per_attempt=measured*1.5/3600
per_completion=125*per_attempt/100
assert abs(per_completion-1.25*per_attempt)<1e-12

Failure overhead belongs in the budget even when it does not count as successful throughput.

Reject impossible capacity inputs

Transfer / diagnosis

Try a full reserve, zero workers and a nonfinite measured duration.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Try a full reserve, zero workers and a nonfinite measured duration.

Outputs

  • Input errors for infeasible reserve, worker count, and service duration.

Invariants to check

  • A capacity report requires reserve below one and finite positive work/service values.

Hints

  • A plan should not silently divide by zero or emit a meaningless worker count.
  • Check all three invalid cases before division.
Your attempt · complete the TODOs
import math

def practice_reject_impossible_capacity_inputs(arrival_rate, service_seconds, reserve, workers):
    """Complete the reject impossible capacity inputs check."""
    # TODO: ('Reject reserve fraction 1, worker count 0, and a nonfinite service duration before computing a plan.', 'Three explicit input rejections.', 'A finite feasible capacity estimate requires positive workers and reserve below one.')
    raise NotImplementedError
Show a hint

A plan should not silently divide by zero or emit a meaningless worker count.

Reveal reference solution and reasoning
Reject impossible capacity inputs · Python solution
# Reject impossible capacity inputs (Transfer / diagnosis)
for change in [dict(reserve_fraction=1.),dict(workers=0),dict(measured_job_s=float('nan'))]:
    inputs=dict(measured_job_s=measured,arrivals_per_hour=600,workers=2,hourly_rate=1.5)
    inputs.update(change)
    try:capacity(**inputs)
    except ValueError:pass
    else:raise AssertionError('invalid plan accepted')

Input validation makes the assumptions visible and prevents numeric output from looking authoritative when the inputs are invalid.

Check your understanding

Which claim is supported by the measured update duty fraction?

Choose one answer

Diagnose the result

If estimated cost is unexpectedly low, check seconds-to-hours conversion, idle reserved capacity and repeated failed attempts. If worker count looks sufficient but latency is poor, inspect burstiness and service-time variation. If longer jobs look faster per example, separate startup amortization from changes in the compiled update itself.

Stage 5 of 5 · Keep Your EvidenceRecord your verification receipt & carry takeaways forward

Carry forward

  • Carry units and assumptions through every capacity calculation.
  • Measured local duration can inform a bounded model without pretending to establish fleet performance.

Keep your evidence

Download evidence template

Keep measured job/update samples and independent unit calculations. Label demand, reserve and price assumptions as hypothetical before deriving a resource plan.

Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.

Saved in this browser. Export or back up your portfolio anytime in My learning.

Save work for this lesson

Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.

Primary references