892. Spot or on-demand GPUs for a training job
Why it matters Most training budgets are decided by how often you checkpoint on cheap preemptible hardware. This is the back-of-envelope that teams use.
Spot GPUs are cheaper but can be interrupted. Use this expected-value model for a job that needs job_hours of compute:
- expected interruptions: interrupts_per_hour * job_hours
- each interruption loses half a checkpoint interval of work plus a restart: checkpoint_every_h / 2 + restart_h hours
- spot hours: job_hours + interruptions * (checkpoint_every_h / 2 + restart_h)
- spot cost = spot_hours * spot_hourly; on-demand cost = job_hours * ondemand_hourly
Write spot_vs_on_demand(job_hours, ondemand_hourly, spot_hourly, interrupts_per_hour, checkpoint_every_h, restart_h).
Inputs: non-negative floats.
Return a dict {"spot_hours", "spot_cost", "ondemand_cost"} (each rounded to 2 decimals) plus "choice": "spot" if the unrounded spot cost is strictly lower, else "on-demand".
def spot_vs_on_demand(job_hours, ondemand_hourly, spot_hourly, interrupts_per_hour, checkpoint_every_h, restart_h)Example 1
Input: spot_vs_on_demand(100, 4.0, 1.5, 0.05, 2, 0.25)
Output: {'spot_hours': 106.25, 'spot_cost': 159.38, 'ondemand_cost': 400.0, 'choice': 'spot'}
Example 2
Input: job_hours = 100, ondemand_hourly = 4.0, spot_hourly = 1.5, interrupts_per_hour = 0.5, checkpoint_every_h = 8, restart_h = 1
Output: {'spot_hours': 350.0, 'spot_cost': 525.0, 'ondemand_cost': 400.0, 'choice': 'on-demand'}
Example 3
Input: job_hours = 10, ondemand_hourly = 2.0, spot_hourly = 1.0, interrupts_per_hour = 0.0, checkpoint_every_h = 1, restart_h = 0
Output: {'spot_hours': 10.0, 'spot_cost': 10.0, 'ondemand_cost': 20.0, 'choice': 'spot'}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Expected interruptions = rate * job_hours.
Hint 2
Lost time per interruption = interval / 2 + restart.
Hint 3
Compare unrounded costs for the choice.
Common mistakes
- Losing a full checkpoint interval each time.
- Charging restart time at the on-demand price.
- Rounding before comparing.
Understand the idea
An interruption at a random point between checkpoints loses half an interval on average, plus the time to restart and reload. Frequent checkpoints make spot almost as reliable as on-demand. In the example, 100 hours with 0.05 interruptions per hour gives 5 interruptions, each losing 1.25 hours, so the job takes 106.25 spot hours.
Shapes and data flow
Scalars in, dict out.