BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimizers18 of 18 in topic

813. Build a one-cycle learning rate schedule

EasyOptimizers

Why it matters PyTorch's OneCycleLR and fastai's fit_one_cycle use this schedule by default.

The one-cycle policy ramps the learning rate up to a peak and then anneals it far below the start. It often trains faster than a constant rate.

Write one_cycle_lr(step, total, lr_max, pct_up=0.3, div=25.0, final_div=1e4) for a 0-based step in [0, total). Let up = int(pct_up * total), lr_start = lr_max / div and lr_end = lr_start / final_div.
- step < up: cosine ramp from lr_start to lr_max: lr_start + (lr_max - lr_start) * (1 - cos(pi * step / up)) / 2
- otherwise: cosine decay from lr_max to lr_end with f = (step - up) / (total - 1 - up): lr_end + (lr_max - lr_end) * (1 + cos(pi * f)) / 2
If total - 1 - up is 0, use f = 1. Return a float.

Functiondef one_cycle_lr(step, total, lr_max, pct_up=0.3, div=25.0, final_div=1e4)

Example 1

Input: one_cycle_lr(0, 100, 0.1)

Output: 0.004

Example 2

Input: step = 30, total = 100, lr_max = 0.1

Output: 0.1

Example 3

Input: step = 99, total = 100, lr_max = 0.1

Output: 4e-07

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

Compute up, lr_start and lr_end first.

Hint 2

Both phases use (1 - cos) / 2 or (1 + cos) / 2 to move smoothly between two values.

Common mistakes
  • Decaying to lr_start instead of the much smaller lr_end.
  • Using total instead of total - 1 so the last step never reaches lr_end.
Understand the idea

Warm-up with a cosine curve avoids early instability; the long cosine decay to a tiny rate lets the model settle into a minimum.

Worked example

lr_max 0.1, div 25: step 0 is 0.004, step 30 of 100 is the peak 0.1, the last step is 0.004 / 10,000.

cosine up for the first pct_up of steps, cosine down to lr_start / final_div after
Topics
Optimizers
Similar questions
  • Add momentum to gradient descentEasy
  • Clip a list of gradients by their combined global normEasy
  • Take a Nesterov momentum stepEasy
  • Compute the Noam warmup learning rateEasy
All Optimizers problems
Report
813 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import math
def one_cycle_lr(step, total, lr_max, pct_up=0.3, div=25.0, final_div=1e4):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS